const http = require('http');
const fs = require('fs')
const path = require('path');

http.createServer((req,res) => {
    let urlObj = new URL(req.url,'http://localhost:8081');

    let pathName = urlObj.pathname;
    let filePath1 = path.join(__dirname,"/index.html")
    let filePath2 = path.join(__dirname,"/list.html")
    let filePath3 = path.join(__dirname,"/upload");
    if (pathName == '/') {
        fs.readFile(filePath1,(e,data) => {
            if (e) {
                console.log(e)
            }
            else{
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
                res.end(data);
            }
        })
    }
    else if (pathName == "/list") {
        fs.readFile(filePath2,(e,data) => {
            if (e) {
                console.log(e)
            }
            else{
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
                res.end(data);
            }
        })
    }
    else if (pathName == "/getlist") {//返回文件夹内图片列表
        let imgArr=[];
        fs.readdir(filePath3,(e,files) => {
            if (e) {
                console.log(e)
                let sendData = JSON.stringify(imgArr);
                res.writeHead(200,{"Content-Type":"text/json"})
                console.log('sendData: ',sendData)
                res.end(sendData); 
            }
            else {
                for (let i = 0; i < files.length; i++) {
                    imgArr.push(files[i])
                    console.log(files[i])
                    console.log(imgArr)
                }
                let sendData = JSON.stringify(imgArr);
                res.writeHead(200,{"Content-Type":"text/plain"})
                console.log('sendData: ',sendData)
                res.end(sendData); 
            } 
             
        })
        
    }
    else if (pathName == '/upload') {  //对上传图片进行处理
        let str ="";
        req.setEncoding("binary");
        req.on('data',chunk => {
            str += chunk;
        })
        req.on('end',() => {
            // console.log(str);
            let dataArr = str.split('\r\n');
            console.log(dataArr)

            //获得文件名字和文件类型--start
            let fileTypeAndName = dataArr[1].split(';')[2];
            // console.log(fileTypeAndName);
            let fileName = fileTypeAndName.slice(11,-1);
            // console.log(fileName);
            //获得文件名字和文件类型--end

            //获得图片数据并进行类型转换--start
            let myDataArr = dataArr.slice(4,dataArr.length-2);
            let myDataStr = myDataArr.join('\r\n');
            // 将图片转换为二进制数据
            let imgData = Buffer.from(myDataStr,"binary");
            //获得图片数据并进行类型转换--end
            
            fs.writeFileSync(path.join(filePath3,"/"+fileName),imgData,{"encoding":"binary"});
            
            res.writeHead(200,{"Content-Type":"text/plain"});
            res.end("upload successfully!");
        })
        
    }
    else{//这里需要对图片的请求进行处理
        let firstPN = pathName.split('/');
        console.log(firstPN);
        if (firstPN[1] == 'upload'&&firstPN[2] != undefined) {//对图片请求中可以返回的部分进行分流
            let childPath = path.join(filePath3,'/'+firstPN[2])
            fs.readFile(childPath,(err,imgData) => {
                if (err) {
                    console.log(err)
                }
                else{
                    //此处应该返回图片数据
                    res.write(imgData);
                    res.end()
                }
            })
        }
        else{//图片请求中无法处理的部分的分流
            console.log("有其他请求:"+pathName)
            res.end()
        }



        
    }
    console.log(pathName)
}).listen(8081);
console.log('server is listening 8081!!');